package com.bite.common.security.service;

import cn.hutool.core.lang.UUID;
import com.bite.common.core.constants.CacheConstants;
import com.bite.common.core.constants.JwtConstants;
import com.bite.common.redis.service.RedisService;
import com.bite.common.core.domain.LoginUser;
import com.bite.common.core.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class TokenService {

    @Autowired
    private RedisService redisService;


    public String createToken(Long userId,String secret,Integer identity,String nickName,String headImage) {
        Map<String,Object> claims=new HashMap<>();
        String userKey = UUID.fastUUID().toString();
        claims.put(JwtConstants.LOGIN_USER_ID,userId);
        claims.put(JwtConstants.LOGIN_USER_KEY,userKey);
        //生成token
        String token = JwtUtils.createToken(claims, secret);
        //往redis中存储敏感信息
        //使用什么数据结构 String
        //tokenKey必须保证唯一且容易管理  便于维护 统一前缀：logintoken:user
        String tokenKey= getTokenKey(userKey);        //String key="logintoken:"+sysUser.getUserId();
        LoginUser loginUser=new LoginUser();
        loginUser.setIdentity(identity);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        //过期时间怎么记录，过期时间应该订多少
        redisService.setCacheObject(tokenKey,loginUser,CacheConstants.EXP, TimeUnit.MINUTES);
        return token;
    }

    //延长redis中存储的敏感消息的时间
    //在身份验证通过之后调用，并且在请求达到controller层之前，在拦截器中调用
    public void extendsToken(Claims claims){
//        Claims claims;
//        try {
//            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息  解析payload中信息  存储着用户唯一标识信息
//            if (claims == null) {
//                log.error("解析token：{}，出现异常",token);
//                return;
//            }
//        } catch (Exception e) {
//            log.error("解析token：{}，出现异常",token,e);
//            return;
//        }
//        String userKey = JwtUtils.getUserKey(claims);  //获取jwt中的key
        String userKey = getUserKey(claims);
        if (userKey==null){
            return;
        }
        String tokenKey= getTokenKey(userKey);
        //剩余180分钟时进行延长
        Long expire = redisService.getExpire(tokenKey, TimeUnit.MINUTES);
        if (expire!=null && expire<CacheConstants.REFRESH_TIME){
            redisService.expire(tokenKey,CacheConstants.EXP, TimeUnit.MINUTES);
        }
    }

    public LoginUser getLoginUser(String token,String secret) {
        String userKey = getUserKey(token, secret);
        if (userKey == null){
            return null;
        }
        return redisService.getCacheObject(getTokenKey(userKey),LoginUser.class);
    }

    public boolean deleteLogin(String token, String secret) {
        String userKey = getUserKey(token, secret);
        if (userKey == null){
            return false;
        }
        return redisService.deleteObject(getTokenKey(userKey));
    }

    public Long getUserId(Claims claims) {
        if (claims == null) return null;
        return Long.valueOf(JwtUtils.getUserId(claims));
    }

    public String getUserKey(Claims claims){
        if (claims == null) return null;
        return JwtUtils.getUserKey(claims);  //获取jwt中的key
    }

    private String getUserKey(String token,String secret){
        Claims claims = getClaims(token, secret);
        if (claims == null) return null;
        return JwtUtils.getUserKey(claims);  //获取jwt中的key
    }

    public Claims getClaims(String token, String secret) {
        Claims claims;
        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息  解析payload中信息  存储着用户唯一标识信息
            if (claims == null) {
                log.error("解析token：{}，出现异常", token);
                return null;
            }
        } catch (Exception e) {
            log.error("解析token：{}，出现异常", token,e);
            return null;
        }
        return claims;
    }

    public void refreshLoginUser(String nickName,String headImage,String userKey){
        String tokenKey = getTokenKey(userKey);
        LoginUser loginUser = redisService.getCacheObject(tokenKey, LoginUser.class);
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(tokenKey,loginUser);
    }


    private String getTokenKey(String userKey){
        return CacheConstants.LOGIN_TOKEN_KEY + userKey;
    }

}
